package com.jack.netty.tcp.server;

import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jack on 15/10/12.
 */
public class ServerSessionManager {

    //clientId-context
    private static Map<String,ChannelHandlerContext> map = new HashMap<String, ChannelHandlerContext>();

    private ServerSessionManager(){

    }

    public static void add(String clientId,ChannelHandlerContext ctx){
        if(map.containsKey(clientId)){
            del(clientId);
        }
        map.put(clientId,ctx);
    }

    public static void del(String clientId){
        if(map.containsKey(clientId)){
            ChannelHandlerContext ctx = map.get(clientId);
            ctx.close();
            map.remove(clientId);
        }
    }

    public static List<ChannelHandlerContext> getContexts(){
        List<ChannelHandlerContext> list = new ArrayList<ChannelHandlerContext>();
        list.addAll(map.values());
        return list;
    }

    public static List<ChannelHandlerContext> getContextExceptOne(String clientId){
        List<ChannelHandlerContext> list = new ArrayList<ChannelHandlerContext>();
        for(String key : map.keySet()){
            if(!key.equals(clientId)){
                list.add(map.get(key));
            }
        }
        return list;
    }

    public static ChannelHandlerContext get(String clientId){
        return map.get(clientId);
    }

}
